<?php
/***********************************************************************
 * @package    	IvanEngine
 * @subpackage 	Core
 * @author     	Ivan <ivanzx@msn.com>
 * @created    	2010-05-19
 ***********************************************************************/
if(defined("IVANENGINE_CORE_VALIDATOR_CHOICE"))
	die("Redefinition macro in :".__FILE__."(".__LINE__.")");
define("IVANENGINE_CORE_VALIDATOR_CHOICE", true);

require_once (dirname(__FILE__).'/ValidatorBase.php');
require_once (dirname(__FILE__).'/../Callback.php');

class CValidatorChoice extends CValidatorBase
{
	const NO_Multiple	= "NO_Multiple";
	const NR_Choices	= "NR_Choices";
	protected function Initialize($options = array(), $messages = array())
  	{
		$this->AddRequiredOption(self::NR_Choices);
    	$this->AddOption(self::NO_Multiple, false);
  	}

  	protected function DoVerify($value)
  	{
		$choices = $this->GetOption(self::NR_Choices);
	    if ($choices instanceof CCallback)
	    {
	      	$choices = $choices->Call();
	    }
	
	    if ($this->GetOption(self::NO_Multiple))
	    {
	      	if (!is_array($value))
	      	{
	        	$value = array($value);
	      	}
	
	      	foreach ($value as $v)
	      	{
		        if (!self::InChoices($v, $choices))
		        {
		          	throw new CExceptionValidator($this, self::NM_Invalid, array('value' => $v));
		        }
	      	}
	    }
	    else
	    {
	      	if (!self::InChoices($value, $choices))
	      	{
	        	throw new CExceptionValidator($this, self::NM_Invalid, array('value' => $value));
	      	}
	    }
	
	    return $value;
  	}
  	
	static protected function InChoices($value, array $choices = array())
  	{
	    foreach ($choices as $choice)
	    {
	      	if ((string) $choice == (string) $value)
	      	{
	        	return true;
	      	}
	    }

    	return false;
  	}
}

?>